package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.Agreement;
import com.woyao.core.model.ApplyResponse;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.CommentSummary;
import com.woyao.core.model.DemandSummary;
import com.woyao.core.model.GetMyDemandResponse;
import com.woyao.core.model.GetPersonResponse;
import com.woyao.core.model.InterestSummary;
import com.woyao.core.model.MediaSummary;
import com.woyao.core.model.NewItemSummary;
import com.woyao.core.model.Person;
import com.woyao.core.service.AccountService;
import com.woyao.core.service.ChanceService;
import com.woyao.core.util.CollectionUtil;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class PersonViewActivity extends AppCompatActivity {

    private Button shareBtn;
    private FrameLayout mainView;

    private  Integer id;
    private Person current = new Person();

    private ClipboardManager myClipboard;
    private ClipData myClip;

    private TextView descTxt;
    private ImageView imageImg;
    private TextView titleTxt;

    private LinearLayout attrsInfo;
    private LinearLayout membersInfo;
    private LinearLayout partnersInfo;
    private LinearLayout demandsInfo;
    private LinearLayout agreementsInfo;
    private LinearLayout updatesInfo;
    ProgressDialog progressDialog;

    private Integer ADD_DEMAND_CODE = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.person_view);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        agreementsInfo = (LinearLayout) findViewById(R.id.agreements_info);
        mainView = (FrameLayout) findViewById(R.id.main_view);
        titleTxt = (TextView) findViewById(R.id.person_title);

        descTxt = (TextView) findViewById(R.id.person_desc);
        imageImg = (ImageView) findViewById(R.id.person_image);


        attrsInfo = (LinearLayout) findViewById(R.id.person_attrs);
        membersInfo = (LinearLayout) findViewById(R.id.person_members);
        partnersInfo = (LinearLayout) findViewById(R.id.person_partners);
        demandsInfo = (LinearLayout) findViewById(R.id.person_demands);
        updatesInfo = (LinearLayout) findViewById(R.id.updates_info);


        Button applyBtn = (Button)findViewById(R.id.person_apply);

        applyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                presentDemandChoice();
            }
        });

        shareBtn = (Button)findViewById(R.id.sharelink);

        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                displayReferContent();
            }
        });

        TextView footerText = (TextView) findViewById(R.id.slogan);
        footerText.setText(footerText.getText() + " " + Common.getCurrentVersion(PersonViewActivity.this));


        Intent intent = getIntent();
        id = intent.getIntExtra("id",0);

        mainView.setVisibility(View.INVISIBLE);
        loadData();


    }

    int demandChoice = 0 ;

    private void presentDemandChoice( ){
        progressDialog = new ProgressDialog(PersonViewActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在处理···");
        progressDialog.show();

        AsyncTask<Void, Void, GetMyDemandResponse> task =new AsyncTask<Void, Void, GetMyDemandResponse>() {
            @Override
            protected GetMyDemandResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyDemandResponse> responseCall = svc.getMyDemand(WoyaoooApplication.userId, "false");
                try {
                    GetMyDemandResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyDemandResponse response) {
                progressDialog.dismiss();
                final List<DemandSummary> demands = response.getContent();

                if (demands.size() ==0 ){

                    new AlertDialog.Builder(PersonViewActivity.this)
                            .setTitle("信息")
                            .setMessage("请说明业务")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    AddDemand();
                                }
                            }).create().show();

                    return;
                }

                ArrayList<String> list = new ArrayList<String>();
                for (int i = 0; i < demands.size(); i++) {
                    DemandSummary ds = demands.get(i);
                    list.add(ds.getTitle());
                }
                list.add( "+ 添加业务");


                String[] items =  (String[])list.toArray(new String[0]);

                AlertDialog.Builder singleChoiceDialog =
                        new AlertDialog.Builder(PersonViewActivity.this);
                singleChoiceDialog.setTitle("发送业务");
                // 第二个参数是默认选项，此处设置为0
                singleChoiceDialog.setSingleChoiceItems(items, demandChoice,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                demandChoice = which;
                            }
                        });
                singleChoiceDialog.setPositiveButton("确 定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (demandChoice != -1) {
                                    if (demandChoice == demands.size()) {
                                        AddDemand();
                                    }else{
                                        applyIt(demands.get(demandChoice).getId() );
                                    }
                                }
                            }
                        });
                singleChoiceDialog.setNegativeButton("取 消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                singleChoiceDialog.show();
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);

    }

    private void applyIt( final Integer demand_id ) {

        AsyncTask<Void, Void, ApplyResponse> task =
                new AsyncTask<Void, Void, ApplyResponse>() {
                    boolean bizComplete = false;

                    @Override
                    protected ApplyResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<ApplyResponse> responseCall = svc.apply(userId, "",0,demand_id  ,0,current.getId());
                        try {
                            ApplyResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final ApplyResponse response) {
                        progressDialog.dismiss();
                        if ( response != null) {
                            if (response.isSuccess()) {
                                Toast.makeText(PersonViewActivity.this,response.getMessage(),Toast.LENGTH_SHORT).show();

                            }else{
                                Common.alert(PersonViewActivity.this, response.getMessage());

                            }

                        }else{
                            Toast.makeText(PersonViewActivity.this,"抱歉,处理失败，请重试。",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute((Void) null);

    }

    public  void AddDemand(){

        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.putExtra("is_new", true);
        intent.setClass(PersonViewActivity.this, DemandNewActivity.class);
        startActivityForResult(intent, ADD_DEMAND_CODE);
    }


    private void displayReferContent() {
        final String text = "Http://www.woyaooo.com/p/" + id + "?rid=" + userId;

        Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle("分享").
                setMessage(text).
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("复制", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                        myClip = ClipData.newPlainText("text", text);
                        myClipboard.setPrimaryClip(myClip);
                    }
                }).
                create();
        alertDialog.show();
    }



//    @Override
//    public void onBackPressed() {
//        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//        if (drawer.isDrawerOpen(GravityCompat.START)) {
//            drawer.closeDrawer(GravityCompat.START);
//        } else {
//            super.onBackPressed();
//        }
//    }



    private void loadData() {


        progressDialog = new ProgressDialog(PersonViewActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("加载···");
        progressDialog.show();

        AsyncTask<Void, Void, GetPersonResponse> task = new AsyncTask<Void, Void, GetPersonResponse>() {
            @Override
            protected GetPersonResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetPersonResponse> responseCall = svc.getPerson(userId, id);
                GetPersonResponse ret = null;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final GetPersonResponse resp) {
                if (resp != null) {
                    if (resp.isSuccess()) {
                        current = resp.getContent();
                        render();
                    } else {
                       Common.alert(PersonViewActivity.this,resp.getMessage());
                    }
                } else {
                    Common.alert(PersonViewActivity.this,"请检查网络后重试！");
                }

                progressDialog.dismiss();

            }

            @Override
            protected void onCancelled() {

                progressDialog.dismiss();
                Common.alert(PersonViewActivity.this,"请检查网络后重试！");

            }
        };
        task.execute((Void) null);

    }


    private void render() {

        this.setTitle( current.getTitle());


        titleTxt.setText(current.getTitle());

        if (StringUtil.notNullOrEmpty(current.getImage())) {
            Picasso.with(this)
                    .load(current.getImage())
                    .into(imageImg);
        } else {
            imageImg.setImageResource(R.drawable.no_avartar);
        }

        descTxt.setText(current.getDescription());



        displayAttrs();

        displayMembers();

        displayAgreements();

//        displayPartners();

        displayDemands();

        displayUpdates();

        mainView.setVisibility(View.VISIBLE);
    }
    private void voteIt( final Integer uid,final String act ) {

        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {

                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);

                        Call<BaseResponse> responseCall = svc.addVote(userId, uid,act);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {
                        if ( response == null || response.isSuccess() == false) {
                            Common.showSnack(PersonViewActivity.this, shareBtn,"抱歉,处理失败，请重试。");
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        Common.showSnack(PersonViewActivity.this, shareBtn,"抱歉,处理失败，请重试。");
                    }
                };
        task.execute((Void) null);

    }
    private void displayUpdates() {

        updatesInfo.removeAllViews();

        if (current.getMoves().size() == 0)
            return;

        if (!current.getMoves_summary().equals("")) {

            LinearLayout item1 = (LinearLayout) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);

            title1.setText(current.getMoves_summary());
            updatesInfo.addView(item1);
        }


        if (CollectionUtil.notEmpty(current.getMoves())) {
            //合作的人
            Integer order = 0;
            for (final InterestSummary interest : current.getMoves()) {
                order  = order  + 1;
                LinearLayout item = (LinearLayout) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.move_item, null);
                final TextView move_order = (TextView) item.findViewById(R.id.move_order);
                final TextView move_subject = (TextView) item.findViewById(R.id.move_subject);
                final TextView move_desc = (TextView) item.findViewById(R.id.move_desc);
                final TextView move_created = (TextView) item.findViewById(R.id.move_created);
                final TextView yes_dig_num = (TextView) item.findViewById(R.id.yes_dig_num);
                final TextView no_dig_num = (TextView) item.findViewById(R.id.no_dig_num);
                final LinearLayout mediaItems = (LinearLayout) item.findViewById(R.id.id_move_medias);
                final ImageView voteUp = (ImageView) item.findViewById(R.id.yesdig);
                final ImageView voteDown = (ImageView) item.findViewById(R.id.nodig);

                final TextView move_displayname = (TextView) item.findViewById(R.id.move_displayname);
                final CircleImageView move_avatar = (CircleImageView) item.findViewById(R.id.move_avatar);

                final LinearLayout moveItem = (LinearLayout) item.findViewById(R.id.moveItem);
                final TextView move_title = (TextView) item.findViewById(R.id.move_title);
                move_title.setText( interest.getTitle());

                moveItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if (interest.getRelation_type().equals("demand")) {
                            Intent intent = new Intent();
                            intent.putExtra("id", interest.getRelation_id());
                            intent.setClass(PersonViewActivity.this, ChanceViewActivity.class);
                            startActivity(intent);
                        }

                        if (interest.getRelation_type().equals("org")) {
                            Intent intent = new Intent();
                            intent.putExtra("id", interest.getRelation_id());
                            intent.setClass(PersonViewActivity.this, OrgViewActivity.class);
                            startActivity(intent);
                        }

                        if (interest.getRelation_type().equals("person")) {
                            Intent intent = new Intent();
                            intent.putExtra("id", interest.getUser_id());
                            intent.setClass(PersonViewActivity.this, PersonViewActivity.class);
                            startActivity(intent);
                        }
                    }
                });


                move_displayname.setText(interest.getDisplayname());

                if (StringUtil.notNullOrEmpty(interest.getSnailview())) {
                    Picasso.with(PersonViewActivity.this)
                            .load(interest.getSnailview())
                            .into(move_avatar);
                } else {
                    move_avatar.setImageResource(R.drawable.no_avartar);
                }

                move_avatar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.putExtra("id", interest.getUser_id());
                        intent.setClass(PersonViewActivity.this, PersonViewActivity.class);
                        startActivity(intent);
                    }
                });
                move_order.setText( order  + "" );

                voteUp.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        yes_dig_num.setText( interest.getPositive() + 1 +"");
                        voteIt( interest.getId(), "up");
                        voteUp.setImageResource(R.drawable.vote_up_grey);
                        voteDown.setImageResource(R.drawable.vote_down_grey);
                    }
                });

                voteDown.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        no_dig_num.setText( interest.getNegative() + 1 +"");
                        voteIt( interest.getId(), "down");
                        voteUp.setImageResource(R.drawable.vote_up_grey);
                        voteDown.setImageResource(R.drawable.vote_down_grey);
                    }
                });

                if  (interest.getVoted()){
                    voteUp.setImageResource(R.drawable.vote_up_grey);
                    voteDown.setImageResource(R.drawable.vote_down_grey);
                }
                move_desc.setText(interest.getDescription());
                move_created.setText(interest.getCreated());
                yes_dig_num.setText(interest.getPositive() +"");
                no_dig_num.setText(interest.getNegative() +"");

                String tempstr = "";
                for (String onestr : interest.getSubject()){
                    tempstr += "#" + onestr +" ";
                }
                move_subject.setText( tempstr ) ;

                for (final MediaSummary ms : interest.getMedias()) {
                    android.support.v7.widget.ContentFrameLayout image_item = (android.support.v7.widget.ContentFrameLayout) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.media_item, null);
                    ImageView imageView = (ImageView) image_item.findViewById(R.id.media_pic);
                    final Button deleteBtn = (Button)image_item.findViewById(R.id.media_delete);
                    final Button playBtn = (Button)image_item.findViewById(R.id.media_play);

                    if (ms.getId().endsWith("mp4")){
                        playBtn.setVisibility(View.VISIBLE);
                    }else{
                        playBtn.setVisibility(View.GONE);
                    }

                    deleteBtn.setVisibility(View.GONE);

                    if (StringUtil.notNullOrEmpty(ms.getSnailview())) {
                        Picasso.with(PersonViewActivity.this)
                                .load(ms.getSnailview())
                                .into(imageView);
                    } else {
                        imageView.setImageResource(R.drawable.no_avartar);
                    }

                    mediaItems.addView(image_item);

                }

                updatesInfo.addView(item);

            }
        }

        View splitter = (View) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.splitter, null);
        updatesInfo.addView(splitter);
    }
    private void displayAgreements() {

        agreementsInfo.removeAllViews();

        if (current.getAgreements().size() == 0)
            return;

        if (!current.getAgreements_summary().equals("")) {

            LinearLayout item1 = (LinearLayout) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);

            title1.setText(current.getAgreements_summary());
            agreementsInfo.addView(item1);
        }


        if (CollectionUtil.notEmpty(current.getAgreements())) {
            //合作的人
            Integer order = 0;
            for (final Agreement agreement : current.getAgreements()) {
                order  = order  + 1;
                LinearLayout item = (LinearLayout) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.agreement_item, null);
                CircleImageView agreement_avatar = (CircleImageView) item.findViewById(R.id.agreement_avatar);
                final TextView agreement_title = (TextView) item.findViewById(R.id.agreement_title);
                final TextView agreement_desc = (TextView) item.findViewById(R.id.agreement_desc);
                final TextView agreement_order = (TextView) item.findViewById(R.id.agreement_order);

                agreement_title.setText(agreement.getTitle());
                agreement_desc.setText(agreement.getDescription());
                agreement_order.setText(order + "");

                if (StringUtil.notNullOrEmpty(agreement.getImage())) {
                    Picasso.with(PersonViewActivity.this)
                            .load(agreement.getImage())
                            .into(agreement_avatar);
                } else {
                    agreement_avatar.setImageResource(R.drawable.no_avartar);
                }

                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.putExtra("id",agreement.getRelation_demand_id() );
                        intent.setClass(PersonViewActivity.this, ChanceViewActivity.class);
                        startActivity(intent);
                    }
                });


                for (final CommentSummary comment : agreement.getComments()) {
                    LinearLayout comment_item = (LinearLayout) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.agreement_comment_item, null);
                    CircleImageView comment_avatar = (CircleImageView) comment_item.findViewById(R.id.comment_avatar);
                    final TextView commentDisplayname = (TextView) comment_item.findViewById(R.id.comment_displayname);
                    final TextView commentTitle = (TextView) comment_item.findViewById(R.id.comment_title);
                    final TextView commentDesc = (TextView) comment_item.findViewById(R.id.comment_desc);
                    final TextView commentRate = (TextView) comment_item.findViewById(R.id.comment_rate);
                    final TextView commentCharge = (TextView) comment_item.findViewById(R.id.comment_charge);
                    final Button viewComment = (Button)comment_item.findViewById(R.id.id_view_comment);
                    final ImageView yesDig = (ImageView) comment_item.findViewById(R.id.yesdig);
                    final ImageView noDig = (ImageView) comment_item.findViewById(R.id.nodig);
                    final TextView dig = (TextView) comment_item.findViewById(R.id.comment_dig);

                    if (comment.getCharge() >0 ) {
                        viewComment.setVisibility(View.VISIBLE);
                        commentCharge.setVisibility(View.VISIBLE);
                        commentCharge.setText( "￥" + comment.getCharge() );
                    }else{
                        viewComment.setVisibility(View.GONE);
                        commentCharge.setVisibility(View.GONE);
                    }

                    commentDesc.setText(comment.getDescription());
                    commentTitle.setText(comment.getTitle());
                    commentDisplayname.setText(comment.getDisplayname());

                    String rateStr = "";
                    for ( int i = 0; i < comment.getRate();i++ ){
                        rateStr = rateStr  +"★";
                    }
                    if (comment.getRate()> 0) {
                        commentRate.setText( rateStr);
                    }else{
                        commentRate.setText("" );
                    }

                    if ( comment.getDiggable() ){
                        yesDig.setVisibility(View.VISIBLE);
                        noDig.setVisibility(View.GONE);
                    }else{
                        yesDig.setVisibility(View.GONE);
                        noDig.setVisibility(View.VISIBLE);
                    }
                    dig.setText(comment.getDig() +"");

                    yesDig.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (comment.getDiggable()) {
                                yesDig.setVisibility(View.GONE);
                                noDig.setVisibility(View.VISIBLE);
                                dig.setText((Integer.parseInt(dig.getText().toString()) + 1) + "");
                                digIt(comment.getId());
                            }
                        }
                    });

                    if (StringUtil.notNullOrEmpty(comment.getSnailview())) {
                        Picasso.with(PersonViewActivity.this)
                                .load(comment.getSnailview())
                                .into(comment_avatar);
                    } else {
                        comment_avatar.setImageResource(R.drawable.no_avartar);
                    }

                    comment_avatar.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent();
                            intent.putExtra("id",comment.getUser_id() );
                            intent.setClass(PersonViewActivity.this, PersonViewActivity.class);
                            startActivity(intent);
                        }
                    });

                    viewComment.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Dialog alertDialog = new AlertDialog.Builder(PersonViewActivity.this).
                                    setTitle("信息").
                                    setMessage("将收取" + comment.getCharge() + "元").
                                    setIcon(R.drawable.ic_launcher).
                                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            loadComment(comment.getId(),commentDesc);
                                        }
                                    }).
                                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).
                                    create();
                            alertDialog.show();
                        }
                    });

                    item.addView(comment_item);
                    View splitter = (View) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.light_splitter, null);
                    item.addView(splitter);
                }

                agreementsInfo.addView(item);

                if (order < current.getAgreements().size()) {
                    View splitter = (View) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.light_splitter, null);
                    agreementsInfo.addView(splitter);
                }
            }
        }

        View splitter = (View) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.splitter, null);
        agreementsInfo.addView(splitter);
    }



    private  void loadComment(final Integer comment_id,final TextView descTxt){
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<BaseResponse> responseCall = svc.getCommentContent(WoyaoooApplication.userId,comment_id);
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {

                    if (response.isSuccess()) {
                        descTxt.setText(response.getMessage());
                        descTxt.setTextColor(getResources().getColor(R.color.red));
                        Toast.makeText(PersonViewActivity.this,"请查看收费评论",Toast.LENGTH_LONG);
                    }else{
                        Common.alert( PersonViewActivity.this,response.getMessage());
                        if (response.getCondition().equals("charge")){
                            renderMoney();
                        }
                    }
//                    Common.alert( ChanceActivity.this,response.getMessage());
                } else {
                    Common.alert( PersonViewActivity.this,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    private void renderMoney( ){
        Intent intent = new Intent();
        intent.putExtra("money", 100.0);
        intent.setClass(PersonViewActivity.this, MoneyActivity.class);
        startActivity(intent);
    }


    private void displayAttrs() {

        attrsInfo.removeAllViews();



        for  ( Map<String,String> oneMap : current.getAttrs()) {
            for (Map.Entry<String, String> entry : oneMap.entrySet()){
                LinearLayout item = (LinearLayout) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.list_item, null);

                TextView title = (TextView) item.findViewById(R.id.title);
                TextView text = (TextView) item.findViewById(R.id.text);
                title.setText(entry.getKey() + ":");
                text.setText(entry.getValue());
                attrsInfo.addView(item);
            }
        }


    }

    private void displayMembers() {

        membersInfo.removeAllViews();

        if (! current.getMembers_summary().equals("")) {
            LinearLayout item1 = (LinearLayout) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);

            title1.setText(current.getMembers_summary());
            membersInfo.addView(item1);
        }

        if (current.getMembers().size() >0 ) {
            for (final NewItemSummary oneItem : current.getMembers()) {
                LinearLayout item = (LinearLayout) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.partner_item, null);
                CircleImageView avatar = (CircleImageView) item.findViewById(R.id.partner_avatar);

                TextView title = (TextView) item.findViewById(R.id.partner_title);
                final TextView desc = (TextView) item.findViewById(R.id.partner_desc);

                title.setText(oneItem.getTitle());
                desc.setText(oneItem.getDescription());


                if (StringUtil.notNullOrEmpty(oneItem.getImage())) {
                    Picasso.with(this)
                            .load(oneItem.getImage())
                            .into(avatar);
                } else {
                    avatar.setImageResource(R.drawable.no_avartar);
                }

                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.setClass(PersonViewActivity.this, OrgViewActivity.class);
                        intent.putExtra("id", oneItem.getId());
                        startActivity(intent);
                    }
                });

                membersInfo.addView(item);
            }
            View splitter = (View) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.splitter, null);
            membersInfo.addView(splitter);
        }

    }

    private void digIt( final Integer comment_id ) {



        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    boolean bizComplete = false;

                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<BaseResponse> responseCall = svc.dig(userId, comment_id);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {
                        if ( response == null || response.isSuccess() == false) {
                            Common.alert(  PersonViewActivity.this , "抱歉,处理失败，请重试。");
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        Common.alert(  PersonViewActivity.this , "抱歉,处理失败，请重试。");
                    }
                };
        task.execute((Void) null);

    }



//    private void alertAndCharge(  ApplyResponse response ){
//
//
//        Dialog alertDialog = new AlertDialog.Builder(this).
//                setTitle("信息").
//                setMessage(response.getMessage()).
//                setIcon(R.drawable.ic_launcher).
//                setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        renderMoney();
//                    }
//                }).
//                create();
//        alertDialog.show();
//    }





    private void displayDemands() {

        demandsInfo.removeAllViews();

        if (! current.getDemands_summary().equals("")) {
            LinearLayout item1 = (LinearLayout) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);

            title1.setText(current.getDemands_summary());
            demandsInfo.addView(item1);
        }

        for (final NewItemSummary oneItem : current.getDemands()) {
            LinearLayout item = (LinearLayout) LayoutInflater.from(PersonViewActivity.this).inflate(R.layout.partner_item_apply, null);
            CircleImageView avatar = (CircleImageView) item.findViewById(R.id.partner_avatar);
            Button applyBtn = (Button) item.findViewById(R.id.id_partner_apply);
            TextView title = (TextView) item.findViewById(R.id.partner_title);
            final TextView desc = (TextView) item.findViewById(R.id.partner_desc);

            title.setText( oneItem.getTitle());
            desc.setText(oneItem.getDescription());


            if (StringUtil.notNullOrEmpty(oneItem.getImage())) {
                Picasso.with(this)
                        .load(oneItem.getImage())
                        .into(avatar);
            } else {
                avatar.setImageResource(R.drawable.no_avartar);
            }
            applyBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.putExtra("id",oneItem.getId() );
                    intent.setClass(PersonViewActivity.this, ChanceViewActivity.class);
                    startActivity(intent);
                }
            });
            item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.putExtra("id",oneItem.getId() );
                    intent.setClass(PersonViewActivity.this, ChanceViewActivity.class);
                    startActivity(intent);
                }
            });

            demandsInfo.addView(item);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == ADD_DEMAND_CODE &&  resultCode == 666 ) {
            presentDemandChoice();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }
}
